/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.gt.web;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.gt.entity.GtInfoDeliver;
import com.thinkgem.jeesite.modules.gt.entity.GtPostPeople;
import com.thinkgem.jeesite.modules.gt.service.GtInfoDeliverService;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 信息宣传Controller
 * @author zad
 * @version 2018-03-26
 */
@Controller
@RequestMapping(value = "${frontPath}/gt/gtInfoDeliver")
public class GtInfoDeliverController extends BaseController {

	@Autowired
	private GtInfoDeliverService gtInfoDeliverService;
	@Autowired
	private AreaService areaService;
	
	@ModelAttribute
	public GtInfoDeliver get(@RequestParam(required=false) String id) {
		GtInfoDeliver entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = gtInfoDeliverService.get(id);
		}
		if (entity == null){
			entity = new GtInfoDeliver();
		}
		return entity;
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(GtInfoDeliver gtInfoDeliver,String menuId, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		this.areaService.fetchRegions(model);
		
		// 信息宣传 查询 时，不做限制 add by zad 2018-04-28
		if(null == gtInfoDeliver.getArea() || StringUtils.isBlank(gtInfoDeliver.getArea().getCode()))
		{
			Area area = UserUtils.getUser().getArea();
			gtInfoDeliver.setArea(area);
		}
		
		Page<GtInfoDeliver> page = gtInfoDeliverService.findPage(new Page<GtInfoDeliver>(request, response), gtInfoDeliver); 
		model.addAttribute("page", page);
		
		model.addAttribute("gtInfoDeliver", gtInfoDeliver);
		model.addAttribute("menuId", menuId);
		
		return "modules/gt/basic/gtInfoDeliverList";
	}

	/**
     * 导出文件
     */
    @RequestMapping("downLoad")
    public void downLoad(String areaId,GtInfoDeliver gtInfoDeliver,String timeStamp, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException{
    	Area area = null;
    	if("undefined".equals(areaId))
    	{
    		areaId = "";
    	}
    	if(!StringUtils.isEmpty(areaId))
		{
			area = this.areaService.get(areaId);
		}
    	
    	response.setCharacterEncoding("utf-8");
    	String fileName = UserUtils.getUser().getArea().getName() + Global.getConfig("exportDeliverFileName");
    	
    	if(null != area)
    	{
    		fileName = area.getName() + Global.getConfig("exportDeliverFileName");
    	}
    	
    	fileName += DateUtils.getDate();
        // fileName = URLEncoder.encode(fileName, "UTF-8");
    	
    	// response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        
        SXSSFWorkbook wb = new SXSSFWorkbook(-1);
        // turn off auto-flushing and accumulate all rows in memory  
        wb.setCompressTempFiles(true); //使用gzip压缩,减小空间占用  
        Sheet sh = wb.createSheet("信息宣传");
        OutputStream out = new BufferedOutputStream(response.getOutputStream());
        try { //从数据库中得到结果  
        	
        	
        	
        	/*if(null == gtInfoDeliver.getArea() || StringUtils.isBlank(gtInfoDeliver.getArea().getCode()))
    		{*/
	        	if(StringUtils.isEmpty(areaId))
	    		{
	    			area = UserUtils.getUser().getArea();
	    		}
    			
    			
    			// gtInfoDeliver.setArea(area);
    			Map<String,String> map = new HashMap<String, String>();
    			map.put("areaCode", area.getCode());
    			
    			
    		/*}*/
        	
        	/*Page<GtInfoDeliver> page = new Page<GtInfoDeliver>();
        	page.setOrderBy("a.update_date");
        	gtInfoDeliver.setPage(page);*/
        	
        	
        	
    		Map<String,String> rs = this.gtInfoDeliverService.findExport(map);
            
    		//设置每一列的宽度,注意 要乘以256,因为1代表excel中一个字符的1/256的宽度  
            sh.setColumnWidth(0, 5 * 256);
            sh.setColumnWidth(1, 10 * 256);
            sh.setColumnWidth(2, 25 * 256);
            sh.setColumnWidth(3, 20 * 256);
            sh.setColumnWidth(4, 20 * 256);
            Row rowHeader = sh.createRow(0);
            /*CellStyle headerStyle = rowHeader.getRowStyle();
            headerStyle.setAlignment(CellStyle.ALIGN_CENTER);*/
            Cell cellHeader = rowHeader.createCell(0);
            cellHeader.setCellValue("序号");
            cellHeader = rowHeader.createCell(1);
            cellHeader.setCellValue("单位");
            cellHeader = rowHeader.createCell(2);
            cellHeader.setCellValue("省级及以上媒体宣传次数");
            cellHeader = rowHeader.createCell(3);
            cellHeader.setCellValue("市级媒体宣传次数");
            cellHeader = rowHeader.createCell(4);
            cellHeader.setCellValue("县级媒体宣传次数");
    		
            if(null == rs || rs.entrySet().size() < 1)
            {
	           /* sh.setColumnWidth(0, 50 * 256);
	        	Row rowHeader = sh.createRow(0);
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("信息提示");
	            
	            Row row = sh.createRow(1);
	            Cell cell = row.createCell(0);  
	            cell.setCellValue("没有找到相关条件的数据。");  */
            	
            	Row row = sh.createRow(1);
                Cell cell = row.createCell(0);  
                cell.setCellValue(1);
                cell = row.createCell(1);
                cell.setCellValue(UserUtils.getUser().getArea().getName());
                cell = row.createCell(2);
                cell.setCellValue("0");  
                cell = row.createCell(3);
                cell.setCellValue("0");
                cell = row.createCell(4);
                cell.setCellValue("0");
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
            }else
            {
	            
	            
	            // 只取5000条数据
	            /*if(null != list && list.size() > Constant.Join.JOIN_EXPORT_MOST_ROWS)
	            {
	            	list.subList(Constant.Join.JOIN_EXPORT_MOST_ROWS, list.size()).clear();
	            }*/
	            
	            // 序号
	            /*int size = list.size();
	            for(int i = 0; i < size; i++) {
	            	
	            	// 当前护林员岗位
	            	GtInfoDeliver deliver = list.get(i);*/
	            	
	                Row row = sh.createRow(1);
	                Cell cell = row.createCell(0);  
	                cell.setCellValue(1);
	                cell = row.createCell(1);
	                cell.setCellValue(rs.get("name"));
	                cell = row.createCell(2);
	                cell.setCellValue(String.valueOf(rs.get("province")));  
	                cell = row.createCell(3);
	                cell.setCellValue(String.valueOf(rs.get("region")));
	                cell = row.createCell(4);
	                cell.setCellValue(String.valueOf(rs.get("country")));
	      
	                /*if(i > 0 && (i % 1000 == 0)) {  
	                    ((SXSSFSheet) sh).flushRows();  
	                } */
	            // }
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
	            
            }
        } catch(Exception e) {
        	sh.setColumnWidth(0, 50 * 256);
        	Row rowHeader = sh.createRow(0);
            Cell cellHeader = rowHeader.createCell(0);
            cellHeader.setCellValue("信息提示");
            
            Row row = sh.createRow(1);
            Cell cell = row.createCell(0);  
            cell.setCellValue("导出失败，请联系管理员。错误信息：" + e.getMessage());  
            
            e.printStackTrace();
            ((SXSSFSheet) sh).flushRows();
            
            CookieUtils.rememberCookieToken(timeStamp,request,response);
            //统一写出方法
            FileUtils.writeWb(wb,out);
        }  
     // 保存日志
     request.setAttribute("title", "用户" + UserUtils.getUser().getLoginName() + "导出了文件：" + fileName);
    }
	
	@RequestMapping(value = "form")
	public String form(String oper,GtInfoDeliver gtInfoDeliver, Model model) {
		
		model.addAttribute("oper", oper);
		
		this.areaService.fetchRegions(model);
		
		// 媒体级别
		List<Dict> mediaTypes = DictUtils.getDictList("gt_media_type");
		model.addAttribute("mediaTypes", mediaTypes);
		
		model.addAttribute("gtInfoDeliver", gtInfoDeliver);
		return "modules/gt/basic/gtInfoDeliverForm";
	}

	@RequestMapping(value = "save")
	public String save(GtInfoDeliver gtInfoDeliver, String oper,Model model,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, gtInfoDeliver)){
			return form(oper,gtInfoDeliver, model);
		}
		

		
		if(StringUtils.isBlank(gtInfoDeliver.getId()))
		{
			// 日志标题
			request.setAttribute("title", "添加信息宣传:" + gtInfoDeliver.getName());
		}else
		{
			// 日志标题
			request.setAttribute("title", "修改信息宣传:" + gtInfoDeliver.getName());
		}
		
		
		
		Map<String,String> fileRs = FileUtils.writeFile(request, "file", "infoDeliver");
		if(null != fileRs)
		{
			gtInfoDeliver.setFileName(fileRs.get("fileName"));
			gtInfoDeliver.setFilePath(fileRs.get("filePath"));
		}
		
		gtInfoDeliverService.save(gtInfoDeliver);
		addMessage(redirectAttributes, "保存信息宣传成功");
		
		if("form".equals(oper))
		{
			return "redirect:"+super.frontPath+"/gt/gtInfoDeliver/form?menuId=" + gtInfoDeliver.getMenuId();
		}
		
		return "redirect:"+super.frontPath+"/gt/gtInfoDeliver?menuId=" + gtInfoDeliver.getMenuId();
	}
	
	@RequestMapping(value = "delete")
	public String delete(GtInfoDeliver gtInfoDeliver,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		gtInfoDeliverService.delete(gtInfoDeliver);
		addMessage(redirectAttributes, "删除信息宣传成功");
		
		
		// 日志标题
		request.setAttribute("title", "删除信息宣传:" + gtInfoDeliver.getId());
		
		
		return "redirect:"+super.frontPath+"/gt/gtInfoDeliver?menuId=" + gtInfoDeliver.getMenuId();
	}

}